package com.yal.predicates;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

//自定义路由断言工厂
//1.类名必须为配置+RoutePredicateFactory
//2.必须继承AbstractRoutePredicateFactory
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory(){
        super(AgeRoutePredicateFactory.Config.class);
    }
    //读取配置文件中参数值，赋值到配置类的中的属性上
    @Override
    public List<String> shortcutFieldOrder(){
        //参数位置必须跟配置文件中的参数对应
        return Arrays.asList("minAge","maxAge");
    }

    //断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                //1.接收前台传入的age参数
                String ageStr=exchange.getRequest().getQueryParams().getFirst("age");

                //2.先判断是否为空，如果不为空，再进行路由逻辑判断
                if (StringUtils.isNotEmpty(ageStr)){
                    int age =Integer.parseInt(ageStr);
                    if(age < config.getMaxAge() && age > config.getMinAge()){
                        return true;
                    }else {
                        return false;
                    }
                }

                return false;
            }
        };
    }


    //配置类，用于接收配置文件中断言配置的参数值
    @Data
    @NoArgsConstructor
    public static class Config{
        private int minAge;
        private int maxAge;
    }
}
